// 道路管理器
import type { DistrictData, RoadConfig, DistrictStyle } from './types'
import { clearOverlays } from './utils'

/**
 * 道路管理器类
 */
export class RoadManager {
  private map: any
  private config: RoadConfig
  private roadOverlays: any[] = []
  private isEnabled: boolean = true
  private currentBoundary: any = null
  private roadSearch: any = null

  constructor(map: any, config: RoadConfig) {
    this.map = map
    this.config = config
    this.isEnabled = config.enableRoad
    // this.initRoadSearch()
  }

  /**
   * 初始化道路搜索服务
   */
  private async initRoadSearch() {
    if (!window.AMap) return

    try {
      // 创建道路搜索服务
      this.roadSearch = new window.AMap.PlaceSearch({
        type: 'bus_stop|subway_station|highway|road', // 搜索道路相关POI
        pageSize: 50,
        pageIndex: 1,
        city: '全国',
        map: this.map,
        panel: false
      })
    } catch (error) {
      console.error('初始化道路搜索服务失败:', error)
    }
  }

  /**
   * 更新道路配置
   */
  updateConfig(config: Partial<RoadConfig>) {
    this.config = { ...this.config, ...config }
    this.isEnabled = this.config.enableRoad
  }

  /**
   * 启用/禁用道路显示
   */
  setEnabled(enabled: boolean) {
    this.isEnabled = enabled
    this.config.enableRoad = enabled
    
    if (!enabled) {
      this.clearRoads()
    }
  }

  /**
   * 在指定区域内显示道路
   * @param district 行政区域数据
   */
  async showRoadsInDistrict(district: DistrictData) {
    if (!this.isEnabled || !district.boundaries) return

    this.clearRoads()
    this.currentBoundary = district.boundaries[0] // 使用第一个边界

    try {
      // 显示主要道路
      await this.showMajorRoads(district)
      
      // 显示次要道路（可选）
      if (this.config.showMinorRoads) {
        await this.showMinorRoads(district)
      }
      
      // 显示高速公路（可选）
      if (this.config.showHighways) {
        await this.showHighways(district)
      }
      
      // 显示地铁线路（可选）
      if (this.config.showSubways) {
        await this.showSubways(district)
      }
    } catch (error) {
      console.error('显示区域道路失败:', error)
    }
  }

  /**
   * 显示主要道路
   */
  private async showMajorRoads(district: DistrictData) {
    if (!window.AMap) return

    try {
      // 创建道路图层
      const roadLayer = new window.AMap.TileLayer.RoadNet({
        zIndex: 10,
        opacity: this.config.roadStyle?.strokeOpacity || 0.8,
        visible: true
      })

      // 添加到地图
      this.map.add(roadLayer)
      this.roadOverlays.push(roadLayer)

      // 如果需要更精确的道路控制，使用矢量道路
      if (this.config.useVectorRoads) {
        await this.createVectorRoads(district)
      }
    } catch (error) {
      console.error('显示主要道路失败:', error)
    }
  }

  /**
   * 创建矢量道路
   */
  private async createVectorRoads(district: DistrictData) {
    if (!this.roadSearch) return

    const bounds = this.getBoundingBox(district.boundaries[0])
    
    // 搜索区域内的道路
    const roadTypes = ['主干道', '次干道', '支路', '快速路']
    
    for (const roadType of roadTypes) {
      try {
        await this.searchRoadsInBounds(roadType, bounds, district)
      } catch (error) {
        console.warn(`搜索${roadType}失败:`, error)
      }
    }
  }

  /**
   * 在边界内搜索道路
   */
  private async searchRoadsInBounds(
    roadType: string, 
    bounds: any, 
    district: DistrictData
  ): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!this.roadSearch) {
        reject(new Error('道路搜索服务未初始化'))
        return
      }

      this.roadSearch.searchInBounds(roadType, bounds, (status: string, result: any) => {
        if (status === 'complete' && result.poiList) {
          this.processRoadResults(result.poiList.pois, district, roadType)
          resolve()
        } else {
          reject(new Error(`搜索${roadType}失败: ${status}`))
        }
      })
    })
  }

  /**
   * 处理道路搜索结果
   */
  private processRoadResults(roads: any[], district: DistrictData, roadType: string) {
    roads.forEach(road => {
      if (this.isPointInDistrict(road.location, district)) {
        this.createRoadMarker(road, roadType)
      }
    })
  }

  /**
   * 创建道路标记
   */
  private createRoadMarker(road: any, roadType: string) {
    if (!window.AMap) return

    const style = this.getRoadStyle(roadType)
    
    // 创建道路标记
    const marker = new window.AMap.Marker({
      position: road.location,
      icon: this.createRoadIcon(roadType),
      title: road.name,
      extData: {
        type: 'road',
        roadType: roadType,
        roadData: road
      }
    })

    // 绑定事件
    marker.on('click', (e: any) => {
      this.onRoadClick(marker, road, roadType)
    })

    marker.on('mouseover', (e: any) => {
      this.onRoadHover(marker, road, roadType, true)
    })

    marker.on('mouseout', (e: any) => {
      this.onRoadHover(marker, road, roadType, false)
    })

    this.map.add(marker)
    this.roadOverlays.push(marker)
  }

  /**
   * 创建道路图标
   */
  private createRoadIcon(roadType: string): any {
    const iconConfig = {
      '主干道': { color: '#ff4d4f', size: [20, 20] },
      '次干道': { color: '#1890ff', size: [16, 16] },
      '支路': { color: '#52c41a', size: [12, 12] },
      '快速路': { color: '#722ed1', size: [24, 24] },
      '高速公路': { color: '#fa8c16', size: [28, 28] },
      '地铁': { color: '#13c2c2', size: [18, 18] }
    }

    const config = iconConfig[roadType] || { color: '#666666', size: [14, 14] }
    
    return new window.AMap.Icon({
      image: this.createRoadIconSVG(config.color, config.size),
      size: new window.AMap.Size(config.size[0], config.size[1]),
      imageSize: new window.AMap.Size(config.size[0], config.size[1])
    })
  }

  /**
   * 创建道路图标SVG
   */
  private createRoadIconSVG(color: string, size: number[]): string {
    return `data:image/svg+xml;base64,${btoa(`
      <svg width="${size[0]}" height="${size[1]}" viewBox="0 0 ${size[0]} ${size[1]}" xmlns="http://www.w3.org/2000/svg">
        <circle cx="${size[0]/2}" cy="${size[1]/2}" r="${Math.min(size[0], size[1])/2 - 1}" 
                fill="${color}" stroke="white" stroke-width="1" opacity="0.9"/>
        <rect x="${size[0]/2 - 2}" y="${size[1]/2 - 1}" width="4" height="2" fill="white"/>
        <rect x="${size[0]/2 - 1}" y="${size[1]/2 - 2}" width="2" height="4" fill="white"/>
      </svg>
    `)}`
  }

  /**
   * 获取道路样式
   */
  private getRoadStyle(roadType: string): any {
    const baseStyle = this.config.roadStyle || {}
    
    const typeStyles = {
      '主干道': { strokeWeight: 4, strokeColor: '#ff4d4f' },
      '次干道': { strokeWeight: 3, strokeColor: '#1890ff' },
      '支路': { strokeWeight: 2, strokeColor: '#52c41a' },
      '快速路': { strokeWeight: 5, strokeColor: '#722ed1' },
      '高速公路': { strokeWeight: 6, strokeColor: '#fa8c16' },
      '地铁': { strokeWeight: 3, strokeColor: '#13c2c2', strokeStyle: 'dashed' }
    }

    return {
      ...baseStyle,
      ...typeStyles[roadType]
    }
  }

  /**
   * 显示次要道路
   */
  private async showMinorRoads(district: DistrictData) {
    // 实现次要道路显示逻辑
    console.log('显示次要道路:', district.name)
  }

  /**
   * 显示高速公路
   */
  private async showHighways(district: DistrictData) {
    if (!this.roadSearch) return

    const bounds = this.getBoundingBox(district.boundaries[0])
    
    try {
      await this.searchRoadsInBounds('高速公路', bounds, district)
    } catch (error) {
      console.warn('显示高速公路失败:', error)
    }
  }

  /**
   * 显示地铁线路
   */
  private async showSubways(district: DistrictData) {
    if (!this.roadSearch) return

    const bounds = this.getBoundingBox(district.boundaries[0])
    
    try {
      await this.searchRoadsInBounds('地铁站', bounds, district)
    } catch (error) {
      console.warn('显示地铁线路失败:', error)
    }
  }

  /**
   * 道路点击事件
   */
  private onRoadClick(marker: any, road: any, roadType: string) {
    // 显示道路信息窗口
    this.showRoadInfo(marker, road, roadType)
    
    // 触发自定义事件
    this.map.emit('road-click', {
      marker,
      road,
      roadType
    })
  }

  /**
   * 道路悬停事件
   */
  private onRoadHover(marker: any, road: any, roadType: string, isHover: boolean) {
    if (isHover) {
      // 高亮显示
      marker.setIcon(this.createHighlightRoadIcon(roadType))
      
      // 显示简单提示
      this.showRoadTooltip(marker, road)
    } else {
      // 恢复原样
      marker.setIcon(this.createRoadIcon(roadType))
      
      // 隐藏提示
      this.hideRoadTooltip()
    }
  }

  /**
   * 创建高亮道路图标
   */
  private createHighlightRoadIcon(roadType: string): any {
    const iconConfig = {
      '主干道': { color: '#ff7875', size: [24, 24] },
      '次干道': { color: '#40a9ff', size: [20, 20] },
      '支路': { color: '#73d13d', size: [16, 16] },
      '快速路': { color: '#9254de', size: [28, 28] },
      '高速公路': { color: '#ffa940', size: [32, 32] },
      '地铁': { color: '#36cfc9', size: [22, 22] }
    }

    const config = iconConfig[roadType] || { color: '#999999', size: [18, 18] }
    
    return new window.AMap.Icon({
      image: this.createRoadIconSVG(config.color, config.size),
      size: new window.AMap.Size(config.size[0], config.size[1]),
      imageSize: new window.AMap.Size(config.size[0], config.size[1])
    })
  }

  /**
   * 显示道路信息
   */
  private showRoadInfo(marker: any, road: any, roadType: string) {
    if (!window.AMap) return

    const content = `
      <div style="
        padding: 12px;
        background: white;
        border-radius: 6px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        min-width: 200px;
      ">
        <div style="font-weight: bold; margin-bottom: 8px; color: #333;">${road.name}</div>
        <div style="margin-bottom: 4px; color: #666; font-size: 12px;">类型: ${roadType}</div>
        <div style="margin-bottom: 4px; color: #666; font-size: 12px;">地址: ${road.address || '未知'}</div>
        <div style="color: #666; font-size: 12px;">坐标: ${road.location.lng.toFixed(6)}, ${road.location.lat.toFixed(6)}</div>
      </div>
    `

    const infoWindow = new window.AMap.InfoWindow({
      content: content,
      offset: new window.AMap.Pixel(0, -30),
      closeWhenClickMap: true
    })

    infoWindow.open(this.map, marker.getPosition())
  }

  /**
   * 显示道路提示
   */
  private showRoadTooltip(marker: any, road: any) {
    if (!window.AMap) return

    const content = `
      <div style="
        padding: 6px 10px;
        background: rgba(0, 0, 0, 0.8);
        color: white;
        border-radius: 4px;
        font-size: 12px;
        white-space: nowrap;
      ">
        ${road.name}
      </div>
    `

    this.currentTooltip = new window.AMap.InfoWindow({
      content: content,
      offset: new window.AMap.Pixel(0, -20),
      closeWhenClickMap: false,
      autoMove: false
    })

    this.currentTooltip.open(this.map, marker.getPosition())
  }

  private currentTooltip: any = null

  /**
   * 隐藏道路提示
   */
  private hideRoadTooltip() {
    if (this.currentTooltip) {
      this.currentTooltip.close()
      this.currentTooltip = null
    }
  }

  /**
   * 判断点是否在行政区域内
   */
  private isPointInDistrict(point: any, district: DistrictData): boolean {
    if (!district.boundaries || !window.AMap) return false

    try {
      const polygon = new window.AMap.Polygon({
        path: district.boundaries[0]
      })
      
      return polygon.contains(point)
    } catch (error) {
      console.warn('判断点是否在区域内失败:', error)
      return false
    }
  }

  /**
   * 获取边界框
   */
  private getBoundingBox(boundary: any[]): any {
    if (!boundary || boundary.length === 0 || !window.AMap) return null

    const lngs = boundary.map(point => point.lng || point[0])
    const lats = boundary.map(point => point.lat || point[1])

    const southwest = new window.AMap.LngLat(Math.min(...lngs), Math.min(...lats))
    const northeast = new window.AMap.LngLat(Math.max(...lngs), Math.max(...lats))

    return new window.AMap.Bounds(southwest, northeast)
  }

  /**
   * 更新道路样式
   */
  updateRoadStyle(style: Partial<DistrictStyle>) {
    this.config.roadStyle = { ...this.config.roadStyle, ...style }
    
    // 重新应用样式到现有道路
    this.roadOverlays.forEach(overlay => {
      if (overlay.setOptions) {
        overlay.setOptions(this.config.roadStyle)
      }
    })
  }

  /**
   * 设置道路类型显示
   */
  setRoadTypeVisible(roadType: string, visible: boolean) {
    this.roadOverlays.forEach(overlay => {
      const extData = overlay.getExtData && overlay.getExtData()
      if (extData && extData.roadType === roadType) {
        overlay.setVisible(visible)
      }
    })
  }

  /**
   * 获取当前显示的道路
   */
  getCurrentRoads(): any[] {
    return this.roadOverlays.filter(overlay => {
      const extData = overlay.getExtData && overlay.getExtData()
      return extData && extData.type === 'road'
    })
  }

  /**
   * 清除所有道路
   */
  clearRoads() {
    clearOverlays(this.map, this.roadOverlays)
    this.hideRoadTooltip()
    this.currentBoundary = null
  }

  /**
   * 获取道路配置
   */
  getConfig(): RoadConfig {
    return { ...this.config }
  }

  /**
   * 销毁道路管理器
   */
  destroy() {
    this.clearRoads()
    this.roadSearch = null
    this.map = null
  }
}